<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI运动指导 - 智能教练对话</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            min-height: 90vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        
        .header h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 2.2em;
        }
        
        .header p {
            color: #666;
            font-size: 1.1em;
        }
        
        .setup-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        
        .input-group {
            margin: 10px 0;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }
        
        .input-group input, .input-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .input-row {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr;
            gap: 15px;
            align-items: end;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.3s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
        }
        
        .btn.secondary {
            background: #6c757d;
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            gap: 20px;
            min-height: 500px;
        }
        
        .chat-main {
            flex: 2;
            display: flex;
            flex-direction: column;
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e0e0e0;
        }
        
        .chat-header {
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .chat-info {
            font-size: 14px;
            color: #666;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            max-height: 400px;
        }
        
        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }
        
        .message.user {
            flex-direction: row-reverse;
        }
        
        .message-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            flex-shrink: 0;
        }
        
        .message.user .message-avatar {
            background: #667eea;
            color: white;
        }
        
        .message.ai .message-avatar {
            background: #4CAF50;
            color: white;
        }
        
        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            line-height: 1.5;
        }
        
        .message.user .message-content {
            background: #667eea;
            color: white;
            border-bottom-right-radius: 4px;
        }
        
        .message.ai .message-content {
            background: #f1f3f4;
            color: #333;
            border-bottom-left-radius: 4px;
        }
        
        .message-time {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
        
        .chat-input {
            padding: 20px;
            border-top: 1px solid #e0e0e0;
            background: #f8f9fa;
            border-radius: 0 0 12px 12px;
        }
        
        .input-with-btn {
            display: flex;
            gap: 10px;
            align-items: stretch;
        }
        
        .input-with-btn input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .sidebar {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .suggestion-panel {
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e0e0e0;
            overflow: hidden;
        }
        
        .panel-header {
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
            font-weight: 600;
            color: #333;
        }
        
        .suggestion-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .suggestion-item {
            padding: 12px 20px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .suggestion-item:hover {
            background: #f8f9fa;
        }
        
        .suggestion-item:last-child {
            border-bottom: none;
        }
        
        .confidence-indicator {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 10px;
        }
        
        .confidence-high { background: #e8f5e8; color: #2e7d32; }
        .confidence-medium { background: #fff3e0; color: #ef6c00; }
        .confidence-low { background: #ffebee; color: #c62828; }
        
        .typing-indicator {
            display: none;
            padding: 10px 16px;
            color: #666;
            font-style: italic;
        }
        
        .status-info {
            background: #e3f2fd;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            border-left: 4px solid #2196F3;
        }
        
        .hidden {
            display: none;
        }
        
        .loading {
            text-align: center;
            color: #666;
            padding: 20px;
        }
        
        .error {
            background: #ffebee;
            color: #c62828;
            padding: 10px 15px;
            border-radius: 8px;
            margin: 10px 0;
            border-left: 4px solid #c62828;
        }
        
        @media (max-width: 768px) {
            .chat-container {
                flex-direction: column;
            }
            
            .input-row {
                grid-template-columns: 1fr;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 AI运动指导</h1>
            <p>基于你的分析结果，获取专业的AI教练指导</p>
        </div>
        
        <div class="setup-section">
            <div class="input-row">
                <div class="input-group">
                    <label for="resultId">分析结果ID:</label>
                    <input type="text" id="resultId" placeholder="输入你的视频分析结果ID" />
                </div>
                <div class="input-group">
                    <label for="sportType">运动类型:</label>
                    <select id="sportType">
                        <option value="running">跑步</option>
                        <option value="basketball_shooting">篮球投篮</option>
                        <option value="tennis_serve">网球发球</option>
                        <option value="golf_swing">高尔夫挥杆</option>
                        <option value="swimming">游泳</option>
                        <option value="general">其他运动</option>
                    </select>
                </div>
                <div class="input-group">
                    <button class="btn" onclick="startAiGuidance()">🚀 开始AI指导</button>
                </div>
            </div>
            <div class="input-group">
                <label for="token">认证Token:</label>
                <input type="password" id="token" placeholder="输入JWT认证token" />
                <small style="color: #666; margin-top: 5px; display: block;">
                    💡 需要先登录获取Token，或使用快速登录功能
                </small>
            </div>
        </div>
        
        <div id="statusInfo" class="status-info hidden">
            <span id="statusText">准备就绪</span>
        </div>
        
        <div id="chatContainer" class="chat-container hidden">
            <div class="chat-main">
                <div class="chat-header">
                    <div>
                        <strong>AI运动教练</strong>
                        <div class="chat-info">
                            会话ID: <span id="conversationIdDisplay">-</span> | 
                            运动类型: <span id="sportTypeDisplay">-</span>
                        </div>
                    </div>
                    <button class="btn secondary" onclick="endConversation()">结束会话</button>
                </div>
                
                <div class="chat-messages" id="chatMessages">
                    <!-- 消息将在这里动态添加 -->
                </div>
                
                <div class="typing-indicator" id="typingIndicator">
                    AI教练正在思考中...
                </div>
                
                <div class="chat-input">
                    <div class="input-with-btn">
                        <input type="text" id="questionInput" placeholder="输入你的问题..." 
                               onkeypress="handleQuestionKeyPress(event)" />
                        <button class="btn" onclick="askQuestion()">发送</button>
                    </div>
                </div>
            </div>
            
            <div class="sidebar">
                <div class="suggestion-panel">
                    <div class="panel-header">💡 推荐问题</div>
                    <div class="suggestion-list" id="suggestionList">
                        <!-- 推荐问题将在这里动态添加 -->
                    </div>
                </div>
                
                <div class="suggestion-panel">
                    <div class="panel-header">📚 会话历史</div>
                    <div class="suggestion-list" id="conversationHistory">
                        <!-- 会话历史将在这里显示 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let currentConversationId = null;
        let currentResultId = null;
        let currentSportType = null;
        
        // 开始AI指导
        async function startAiGuidance() {
            const resultId = document.getElementById('resultId').value.trim();
            const sportType = document.getElementById('sportType').value;
            const token = document.getElementById('token').value.trim();
            
            if (!resultId) {
                alert('请输入分析结果ID');
                return;
            }
            
            if (!token) {
                alert('请输入认证Token');
                return;
            }
            
            try {
                showStatus('正在创建AI指导会话...', 'info');
                
                const response = await fetch(`http://localhost:8085/ai-guidance/conversation?resultId=${encodeURIComponent(resultId)}&sportType=${encodeURIComponent(sportType)}&userId=1`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token.replace(/[^\x00-\xFF]/g, '')}`
                    }
                });
                
                const data = await response.json();
                
                if (data.code === 0) {
                    currentConversationId = data.data.conversationId;
                    currentResultId = resultId;
                    currentSportType = sportType;
                    
                    // 显示聊天界面
                    document.getElementById('chatContainer').classList.remove('hidden');
                    document.getElementById('conversationIdDisplay').textContent = currentConversationId;
                    document.getElementById('sportTypeDisplay').textContent = getSportDisplayName(sportType);
                    
                    // 显示欢迎消息
                    if (data.data.messages && data.data.messages.length > 0) {
                        data.data.messages.forEach(msg => {
                            if (msg.senderType === 'AI_ASSISTANT') {
                                addMessage('ai', msg.content, new Date(msg.timestamp));
                            }
                        });
                    }
                    
                    // 加载推荐问题
                    loadSuggestedQuestions(data.data.suggestedQuestions);
                    
                    showStatus('AI指导会话已开始！你可以开始提问了。', 'success');
                    
                } else {
                    showStatus('创建会话失败: ' + data.message, 'error');
                }
                
            } catch (error) {
                console.error('创建AI指导会话失败:', error);
                showStatus('创建会话失败: ' + error.message, 'error');
            }
        }
        
        // 提问
        async function askQuestion(questionText = null) {
            const question = questionText || document.getElementById('questionInput').value.trim();
            const token = document.getElementById('token').value.trim();
            
            if (!question) {
                alert('请输入问题');
                return;
            }
            
            if (!currentConversationId) {
                alert('请先开始AI指导会话');
                return;
            }
            
            try {
                // 添加用户消息到界面
                addMessage('user', question, new Date());
                
                // 清空输入框
                if (!questionText) {
                    document.getElementById('questionInput').value = '';
                }
                
                // 显示AI正在思考
                showTypingIndicator(true);
                
                const request = {
                    conversationId: currentConversationId,
                    resultId: currentResultId,
                    sportType: currentSportType,
                    question: question
                };
                
                const response = await fetch('http://localhost:8085/ai-guidance/ask', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token.replace(/[^\x00-\xFF]/g, '')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(request)
                });
                
                const data = await response.json();
                
                showTypingIndicator(false);
                
                if (data.code === 0) {
                    // 添加AI回复到界面
                    addMessage('ai', data.data.aiResponse, new Date(), data.data.confidence);
                    
                    // 更新推荐问题
                    if (data.data.suggestedQuestions && data.data.suggestedQuestions.length > 0) {
                        loadSuggestedQuestions(data.data.suggestedQuestions);
                    }
                    
                } else {
                    addMessage('ai', '抱歉，我遇到了一些问题：' + data.message, new Date(), 0);
                }
                
            } catch (error) {
                console.error('提问失败:', error);
                showTypingIndicator(false);
                addMessage('ai', '抱歉，网络连接出现问题，请稍后重试。', new Date(), 0);
            }
        }
        
        // 添加消息到聊天界面
        function addMessage(sender, content, timestamp, confidence = null) {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}`;
            
            const avatar = sender === 'user' ? '👤' : '🤖';
            const confidenceHtml = confidence !== null ? 
                `<span class="confidence-indicator ${getConfidenceClass(confidence)}">置信度: ${confidence}%</span>` : '';
            
            messageDiv.innerHTML = `
                <div class="message-avatar">${avatar}</div>
                <div class="message-content">
                    ${content.replace(/\n/g, '<br>')}
                    ${confidenceHtml}
                    <div class="message-time">${formatTime(timestamp)}</div>
                </div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        // 加载推荐问题
        function loadSuggestedQuestions(questions) {
            const suggestionList = document.getElementById('suggestionList');
            suggestionList.innerHTML = '';
            
            if (!questions || questions.length === 0) {
                suggestionList.innerHTML = '<div class="suggestion-item">暂无推荐问题</div>';
                return;
            }
            
            questions.forEach(question => {
                const suggestionDiv = document.createElement('div');
                suggestionDiv.className = 'suggestion-item';
                suggestionDiv.textContent = question;
                suggestionDiv.onclick = () => {
                    document.getElementById('questionInput').value = question;
                    askQuestion(question);
                };
                suggestionList.appendChild(suggestionDiv);
            });
        }
        
        // 显示状态信息
        function showStatus(message, type) {
            const statusInfo = document.getElementById('statusInfo');
            const statusText = document.getElementById('statusText');
            
            statusText.textContent = message;
            statusInfo.className = `status-info ${type === 'error' ? 'error' : ''}`;
            statusInfo.classList.remove('hidden');
            
            if (type === 'success') {
                setTimeout(() => {
                    statusInfo.classList.add('hidden');
                }, 3000);
            }
        }
        
        // 显示/隐藏AI正在思考指示器
        function showTypingIndicator(show) {
            const indicator = document.getElementById('typingIndicator');
            indicator.style.display = show ? 'block' : 'none';
        }
        
        // 处理Enter键发送
        function handleQuestionKeyPress(event) {
            if (event.key === 'Enter') {
                askQuestion();
            }
        }
        
        // 结束会话
        async function endConversation() {
            if (!currentConversationId) {
                return;
            }
            
            const token = document.getElementById('token').value.trim();
            
            try {
                const response = await fetch(`http://localhost:8085/ai-guidance/conversation/${currentConversationId}/end`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token.replace(/[^\x00-\xFF]/g, '')}`
                    }
                });
                
                const data = await response.json();
                
                if (data.code === 0) {
                    addMessage('ai', '👋 感谢使用AI运动指导！会话已结束，希望这些建议对你有帮助。', new Date());
                    currentConversationId = null;
                    showStatus('会话已结束', 'success');
                }
                
            } catch (error) {
                console.error('结束会话失败:', error);
            }
        }
        
        // 获取置信度样式类
        function getConfidenceClass(confidence) {
            if (confidence >= 80) return 'confidence-high';
            if (confidence >= 60) return 'confidence-medium';
            return 'confidence-low';
        }
        
        // 格式化时间
        function formatTime(date) {
            return date.toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
        }
        
        // 获取运动类型显示名称
        function getSportDisplayName(sportType) {
            const names = {
                'running': '跑步',
                'basketball_shooting': '篮球投篮', 
                'tennis_serve': '网球发球',
                'golf_swing': '高尔夫挥杆',
                'swimming': '游泳',
                'general': '其他运动'
            };
            return names[sportType] || sportType;
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('AI指导界面初始化完成');
            
            // 从URL参数中获取参数
            const urlParams = new URLSearchParams(window.location.search);
            const resultIdFromUrl = urlParams.get('resultId');
            const sportTypeFromUrl = urlParams.get('sportType');
            
            if (resultIdFromUrl) {
                document.getElementById('resultId').value = resultIdFromUrl;
                console.log('📥 从URL获取结果ID:', resultIdFromUrl);
            }
            
            if (sportTypeFromUrl) {
                document.getElementById('sportType').value = sportTypeFromUrl;
                console.log('📥 从URL获取运动类型:', sportTypeFromUrl);
            }
            
            // 从本地存储加载token
            const storedToken = localStorage.getItem('authToken');
            if (storedToken) {
                document.getElementById('token').value = storedToken;
                
                // 如果有完整参数，自动开始AI指导
                if (resultIdFromUrl && sportTypeFromUrl) {
                    console.log('🚀 自动启动AI指导...');
                    setTimeout(() => {
                        startAiGuidance();
                    }, 1000);
                }
            }
        });
    </script>
</body>
</html> 